/***********************************************************
 * Author: 	Brandon McKune
 * E-Mail:	bmckune.cs@gmail.com
 * Date:	September 2, 2011
 * Class:	CSc 8370 - Data Security
 * Time:	1150 - 1325
 * Smstr:	Fall 2011
 */

#include "FileHandler.h"

/**
 * 	Function: FileHandler()
 * 	Description:
 * 		Default constructor of the object called "FileHandler".
 *
 */
FileHandler::FileHandler(){
	this->m_pFile = NULL;
	this->m_prgBuffer = NULL;
}

FileHandler::~FileHandler(){
	this->closeFile();
	this->cleanBuffer();
}

bool FileHandler::loadFile(string filename){
	//Cannot open file of an empty string
	if(filename.empty()){
		fprintf(stderr, "Filename is empty.\n");
		return false;
	}

	//Attempt to close the file if one exists.
	this->closeFile();

	m_pFile = fopen(filename.c_str(), "r");

	if(m_pFile == NULL){
		perror("Failure to load file: ");
		return false;
	}

	//Get the size of the file to create the internal buffer.
	fseek(m_pFile, 0, SEEK_END);
	m_ui64SizeOfFile = ftell(m_pFile);
	rewind(m_pFile);

	m_prgBuffer = (char*)malloc (sizeof(char)*m_ui64SizeOfFile + 1);
	if(m_prgBuffer == NULL){ //malloc failed
		fprintf(stderr, "malloc() read buffer failed.\n");
		this->closeFile();
		return false;
	}

	UINT temp_ui64BytesRead = 0;
	temp_ui64BytesRead = fread(m_prgBuffer, BYTE, m_ui64SizeOfFile, m_pFile);

	if(temp_ui64BytesRead != m_ui64SizeOfFile){
		fprintf(stderr, "There was an error while reading the file.\n");
		this->closeFile();
		return false;
	}

	this->m_prgBuffer[this->m_ui64SizeOfFile] = '\0';

	return true;
}

char* FileHandler::getBuffer(){
	//If the buffer is empty, send NULL
	if(this->m_prgBuffer == NULL){
		return NULL;
	}

	char* returnBuffer = (char*)malloc(this->m_ui64SizeOfFile * sizeof(char) + 1);
	memcpy(returnBuffer, this->m_prgBuffer, m_ui64SizeOfFile + 1);

	return returnBuffer;
}

UINT FileHandler::getBufferSize(){
	return this->m_ui64SizeOfFile;
}
/***********************************************************
 * Protected Functional Members
 */
bool FileHandler::closeFile(){
	if(this->m_pFile != NULL){
		fclose(m_pFile);
		m_pFile = NULL;
	}
	return true;
}

bool FileHandler::cleanBuffer(){
	if(this->m_prgBuffer != NULL){
		free(m_prgBuffer);
		m_prgBuffer = NULL;
	}
	return true;
}
